<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="bg-container" style="justify-content: flex-end">
                <Toolbar :items="pageData.btnList" @select="selectHandler" @add="addHandler"
                         @del="deleteHandler" @export="exports" @import="importHandler"
                         @excel="downloadHandler"></Toolbar>
            </div>
        </template>

        <template #pageTabel>
            <a-tabs   :lazy-load="true" :justify="true">
                <a-tab-pane title="产品单位列表">
                    <!-- <a-table style="height:100%" size="mini" :scrollbar="true" sticky-header
                             @page-change="pagination.change" stripe :bordered="true" :columns="tableColumns"
                             :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                             v-model:selected-keys="selectedRowKeys" :loading="table.tableLoading"
                             :data="table.dataList"
                             :pagination="{ size:'small', current:pagination.page,pageSize:pagination.pageSize,total:pagination.total,showPageSize:false,pageSizeOptions:[10,20,30,50,100]}"
                             :rowKey="rowKey">
                        <template #obsoleteState="{ record }">
                            <a-space size="large">
                                <a-switch checked-color="#F53F3F" unchecked-color="#14C9C9"
                                          v-model="record.obsoleteState" :checked-value="1" :unchecked-value="0"
                                          disabled>
                                    <template #checked>
                                        停用
                                    </template>
                                    <template #unchecked>
                                        启用
                                    </template>
                                </a-switch>
                            </a-space>
                        </template>
                                               <template #deleteState="{ record }">-->
                        <!--                            <a-button v-if="record.deleteState == 1" type="primary" size="small" status="warning" disabled>已删除-->
                        <!--                            </a-button>-->
                        <!--                        </template>-->
                        <!-- <template #edit="{ record }">
                            <a-button v-if="pageData.isEdit" type="primary" size="small" status="warning"
                                      @click="editHandler(record)">
                                <template #icon>
                                    <icon-edit/>
                                </template>
                                修 改
                            </a-button>
                        </template> -->
                        <!-- <template #obsoleteState="{record}">
                        <a-button type="text" status="danger">{{record.obsoleteState==1?"已作废":""}}</a-button>
                    </template> -->
                    <!-- </a-table> --> 

                      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"  @grid-ready="gridReady" style="height:100%" :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc"></AgGridVuesCopys>
                </a-tab-pane>

            </a-tabs>
        </template>
        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{'zIndex':9999}" :mask-closable="false" :width="400"
                  :visible="pageData.showAdd" unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false"
        >
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="vertical" :model="dataForm">
                    <a-form-item label="编号" field="productUnitCode"
                                 :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                                 :validate-trigger="['change', 'blur']">
                        <a-input placeholder="" v-model="dataForm.productUnitCode" @blur="inputBlur"/>
                    </a-form-item>
                    <a-form-item label="单位" field="unit" :rules="[{ required: true, message: '单位必填' }]"
                                 :validate-trigger="['change', 'blur']">
                        <a-input placeholder="" v-model="dataForm.unit"/>
                    </a-form-item>
                    <a-form-item label="是否停用" field="obsoleteState">
                        <a-switch checked-color="#F53F3F" unchecked-color="#14C9C9" v-model="dataForm.obsoleteState"
                                  :checked-value="1" :unchecked-value="0" style="width:65px;">
                            <template #checked>
                                停用
                            </template>
                            <template #unchecked>
                                启用
                            </template>
                        </a-switch>
                    </a-form-item>
                    <a-form-item label="备注" field="remark">
                        <a-input  v-model="dataForm.remark"/>
                    </a-form-item>

                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>

<script lang="ts">
    import {post} from '@/api/http'
    import {useTable, useRowKey, useTableColumn, usePagination, useRowSelection} from '@/hooks/table';

    import {ref, reactive, onMounted, toRefs} from 'vue'
    import Toolbar from '@/components/Toolbar.vue';
    import {Form, Message, Modal} from '@arco-design/web-vue';
    import {FormInstance} from '@arco-design/web-vue/es/form';
    import {addListener} from 'process';
    import {log} from 'console';
    import {baseURL} from '../../../api/axios.config'
    import axios from "axios";
    import filedownload from 'js-file-download'
    import usePermission from '@/store/modules/permission'
    
    interface MaterialGradeInfo {

        "unit": string | undefined,
        "productUnitCode": any,
        "createTime": string | undefined,
        "deleteState": number | string,
        "remark": string | undefined,
        "updateTime": string | undefined,
        "id": any,
        "updateName": string | undefined,
        "isDeadStatus": number,
        "createName": string | undefined,
        "obsoleteState": number | undefined,
    }

    export default {
        name: "ProductUnit",
        setup() {

            function doRefresh() {
                pageData.pageLoading = true
                post({
                    url: "product/productUnit/select",

                    data: {
                        page: pagination.page,
                        size: pagination.pageSize,
                        deleteState: 0
                    },
                })
                    .then(({data, code}: any) => {
                        if (code === 200) {
                            gridOption.value.setRowData(data.list)
                            table.handleSuccess(data.list);
                            pagination.setTotalSize(data.total);
                        }
                    })
                    .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
            }

            const {selectedRowKeys, onSelectionChange} = useRowSelection();
            const pagination = usePagination(doRefresh);
            const table = useTable();
            const rowKey = useRowKey("id");
            const tableColumns = useTableColumn([
                {
                    title: "编码",
                    key: "productUnitCode",
                    dataIndex: "productUnitCode",
                    width: 150,
                },

                {
                    title: "单位",
                    key: "unit",
                    dataIndex: "unit",
                    width: 150,
                },
                {
                    title: "备注",
                    key: "remark",
                    dataIndex: "remark",
                    width: 150,
                },

                {
                    title: "创建人",
                    key: "createName",
                    dataIndex: "createName",
                    width: 150,
                },
                {
                    title: "创建时间",
                    key: "createTime",
                    dataIndex: "createTime",
                    width: 150,
                },
                {
                    title: "最后修改人",
                    key: "updateName",
                    dataIndex: "updateName",
                    width: 150,
                },
                {
                    title: "最后修改时间",
                    key: "updateTime",
                    dataIndex: "updateTime",
                    width: 150,
                },
                {
                    title: "是否停用",
                    key: "obsoleteState",
                    dataIndex: "obsoleteState",
                    slotName: 'obsoleteState',
                    width: 150,
                    fixed: 'right'

                },
                // {
                //     title: "删除状态",
                //     key: "deleteState",
                //     dataIndex: "deleteState",
                //     width: 100,
                //     slotName: "deleteState",
                //     fixed: 'right'
                // },
                {
                    title: "操作",
                    key: "edit",
                    dataIndex: "edit",
                    slotName: 'edit',
                    width: 150, fixed: 'right'
                },
            ]);
            const gridOption = ref()
        const gridReady = (params:any) =>{
            gridOption.value = params.api
        }
            const dataForm = reactive<MaterialGradeInfo>({

                "unit": "",
                "productUnitCode": "",
                "createTime": "",
                "deleteState": 0,
                "remark": "",
                "updateTime": "",
                "id": null,
                "updateName": "",
                "isDeadStatus": 0,
                "createName": "",
                "obsoleteState": 0,

            })
            const pageData = reactive<{

                showAdd: boolean,
                sideTitle: string,
                pageLoading: boolean,
                rHeight: any
                btnList: any[],
                isEdit: boolean
            }>({

                showAdd: false,
                sideTitle: '新增产品单位列表',
                pageLoading: false,
                rHeight: "",
                btnList: [],
                isEdit: false
            });
            const formRef = ref<FormInstance>()

            onMounted(() => {

            });

            const addHandler = () => {
                for (var key in dataForm) {
                    if (key === "id") {
                        dataForm[key] = null;
                    } else {
                        dataForm[key] = "";
                    }

                }
                pageData.showAdd = true
                pageData.sideTitle = '新增产品单位列表'

            }
            //修改 record（本行数据）
            const editHandler = (record: any) => {
                dataForm.id = record.id

                dataForm.productUnitCode = record.productUnitCode
                dataForm.unit = record.unit
                dataForm.remark = record.remark
                //侧滑栏滑出滑入
                pageData.showAdd = true
                pageData.sideTitle = '修改产品单位列表'

            }


            const sideOk = () => {
                formRef.value?.validate().then((err) => {
                    if (pageData.sideTitle === '新增产品单位列表') {
                        //添加
                        if (!err) {
                            post({
                                url: 'product/productUnit/add',
                                data: [dataForm]
                            }).then((res: any) => {

                                if (res.code === 200) {
                                    doRefresh()
                                    formRef.value?.resetFields()

                                    pageData.showAdd = false
                                    Message.success({
                                        content: '新增成功',
                                        duration: 5000
                                    })

                                } else {
                                    Message.error({
                                        content: res.message,
                                        duration: 5000
                                    })
                                }
                            })
                        }
                    } else if (pageData.sideTitle === '修改产品单位列表') {
                        //修改
                        post({
                            url: "product/productUnit/update",
                            data: [dataForm]
                        }).then(({data, code, message}: any) => {
                            if (code === 200) {
                                formRef.value?.resetFields()
                                Message.success({
                                    content: '修改成功',
                                    duration: 5000
                                })
                                doRefresh()
                                pageData.showAdd = false

                            } else {
                                Message.error({
                                    content: message,
                                    duration: 5000
                                })
                            }
                        });
                    }


                })
            }
            const deleteHandler = () => {
                
                if (gridOption.value.getSelectedRows().length === 0) {
                return
            }
                Modal.confirm({
                    title: '系统提示',
                    content: '确认删除选中的数据?',
                    onOk() {
                        post({
                            url: 'product/productUnit/deleteZT',
                            data: gridOption.value.getSelectedRows().map((o:any)=>{return o.id}),
                        }).then(({code, data}: any) => {
                            if (code === 200) {
                                Message.success({
                                    content: '删除成功',
                                    duration: 5000
                                })
                                pagination.page = 1
                                doRefresh()
                            } else {
                                Message.error({
                                    content: '删除失败',
                                    duration: 5000
                                })
                            }

                        })
                    }
                })
            }


            //判断是否填写了中文
            const isChiese = (value: string, cb: Function) => {
                return new Promise<void>(resolve => {
                    if (window.encodeURI(value).indexOf('%') !== -1) {
                        cb('填写的值不能包含中文！')
                    }
                    resolve()
                })

            }
            //input离开焦点 将小写转大写
            const inputBlur = () => {
                dataForm.productUnitCode = dataForm.productUnitCode.toUpperCase();
            }
            const selectHandler = () => {
                doRefresh()
            }
            //导出
            const exports = () => {
                if (selectedRowKeys.value.length === 0) {
                    Message.error('请先勾选')
                    return
                } else {
                    //将表头拼接出来
                    let head = "<th>编号</th><th>单位</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                    //拿到当前表格数据与勾选的行做筛选

                    let nowRow = table.dataList.filter(function (o) {
                        return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                    })
                    let body = "";
                    nowRow.forEach(function (o) {
                        body += "<tr><td>" + o["productUnitCode"] + "</td>";
                        body += "<td>" + o["unit"] + "</td>";
                        body += "<td>" + o["remark"] + "</td>";
                        body += "<td>" + o["createName"] + "</td>";
                        body += "<td>" + o["createTime"] + "</td>";
                        body += "<td>" + o["updateName"] + "</td>";
                        body += "<td>" + o["updateTime"] + "</td>";
                        body += "</tr>";
                    })
                    tableToXlsx(head, '布类资料', body)
                    console.log(table)
                }
            }

            function tableToXlsx(head: any, filename: any, body: any) {
                const uri = 'data:application/vnd.ms-excel;base64,',
                    template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

                const a = document.createElement('a');
                a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
                a.download = filename;
                a.click();
                document.removeChild(a);
            }

            //模板下载
            const downloadHandler = () => {
                axios.get(baseURL + '/product/productUnit/uploadProductUnitModel', {
                    responseType: 'blob',
                    headers: {
                        token: sessionStorage.getItem('USER-TOKEN-KEY')
                    }
                }).then((res) => {
                    if (res.status === 200) {
                        filedownload(res.data, '产品单位.xlsx')
                    }
                })
            }
            //导入
            const importHandler = () => {

                const inputEle: HTMLInputElement = document.createElement('input')
                inputEle.type = 'file'
                inputEle.id = 'fileUploadExcel'
                inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
                inputEle.addEventListener('change', (e) => {
                    const formData = new FormData()
                    if (inputEle.files !== null) {
                        formData.append('file', inputEle.files[0] || '')
                    } else {
                        Message.warning('未选择文件！');
                        return
                    }
                    pageData.pageLoading = true
                    axios.post(baseURL + '/product/productUnit/analyseProductUnitModel', formData, {
                        headers: {
                            "Content-Type": 'multipart/form-data',
                            "token": sessionStorage.getItem('USER-TOKEN-KEY')
                        },
                    }).then((result) => {
                        if (result.data['code'] === 200) {
                            Message.success('导入成功')
                        } else {
                            Message.error(result.data.message)
                        }

                    }).finally(() => {
                        pageData.pageLoading = false
                        doRefresh()
                    })
                })
                inputEle.click()
            }
            //设置权限
            // ['查询', '新增', '删除', '导出', '导入']
            const permissionStore = usePermission()

            if (permissionStore.hasPermisson('cpdwlb.cx')) {

                pageData.btnList.push("查询")
            }
            if (permissionStore.hasPermisson('cpdwlb.xz')) {
                pageData.btnList.push("新增")
            }
            if (permissionStore.hasPermisson('cpdwlb.sc')) {
                pageData.btnList.push("删除")
            }
            if (permissionStore.hasPermisson('cpdwlb.dc')) {
                pageData.btnList.push("导出")
            }
            if (permissionStore.hasPermisson('cpdwlb.dr')) {
                pageData.btnList.push("导入")
            }
            if (permissionStore.hasPermisson('cpdwlb.xg')) {
                pageData.isEdit = true
            }
            let tc:any[] = tableColumns.map((o:any)=>{

let obj = {
    headerName:o.title,
    field:o.key,
    pinned:o['fixed']
}
if(o.slotName === 'action'){
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj["lockPosition"]="right"

    obj['cellRenderer'] = {
        template:`<a-tag class="tagCss" @click="a">修改</a-tag>`,
        setup(props:any){
            const a = () =>{
                editHandler(props.params.data)
            }
            return {
                a
            }
        }
        
    }
}

return obj
})

let a = [{
showRowGroup: 'hide_def',
"headerName": "",
"checkboxSelection": true,
"headerCheckboxSelection": true,
"pinned": "left",
"width": 50,
resizable: false,
filter:false,
sortable:false,
minWidth: 50,
maxWidth: 50,
lockPosition:"left",
}]
tc = a.concat(tc)
        const defaultColDef = {
            sortable: true,
            resizable:true,
            filter: true,
            // flex: 1
          }
            return {
                defaultColDef,
                 tc,
                selectHandler,
                deleteHandler,
                sideOk,
                formRef,
                dataForm,
                addHandler,
                selectedRowKeys,
                pagination,
                tableColumns,
                table,
                rowKey,
                pageData,

                editHandler,
                isChiese,
                inputBlur,
                exports,
                downloadHandler,
                importHandler,
                gridReady

            };
        },
        components: {Toolbar, }
    }
</script>
<style scoped lang="less">


    .toolbar-item {
        cursor: pointer;
    }
</style>